package com.example.wzdjcrdpassword.controller;

import com.example.wzdjcrdpassword.common.ApiResponse;
import com.example.wzdjcrdpassword.common.ErrorCode;
import com.example.wzdjcrdpassword.dto.CombinedValidationRequest;
import com.example.wzdjcrdpassword.entity.CardPassword;
import com.example.wzdjcrdpassword.entity.Config;
import com.example.wzdjcrdpassword.entity.UserReport;
import com.example.wzdjcrdpassword.service.CardPasswordService;
import com.example.wzdjcrdpassword.service.ConfigService;
import com.example.wzdjcrdpassword.service.UserReportService;
import com.example.wzdjcrdpassword.util.RequestContextUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/validation")
@RequiredArgsConstructor
@Slf4j
public class ValidationController {
    
    private final CardPasswordService cardPasswordService;
    private final ConfigService configService;
    private final UserReportService userReportService;
    
    /**
     * 卡密验证接口
     * @param cardPassword 卡密
     * @return 验证结果
     */
    @PostMapping("/card-password")
    public ResponseEntity<Map<String, Object>> validateCardPassword(@RequestParam String cardPassword) {
        // 记录调用来源信息
        String appId = RequestContextUtil.getCurrentAppId();
        String systemName = RequestContextUtil.getCurrentSystemName();
        log.info("卡密验证请求 - appId: {}, 系统名称: {}, 卡密: {}", appId, systemName, cardPassword);
        
        boolean isValid = cardPasswordService.validateCardPassword(cardPassword);
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("data", Map.of(
            "cardPassword", cardPassword,
            "isValid", isValid
        ));
        
        if (isValid) {
            Optional<CardPassword> cardPasswordInfo = cardPasswordService.getCardPasswordInfo(cardPassword);
            cardPasswordInfo.ifPresent(info -> {
                response.put("cardInfo", Map.of(
                    "expireTime", info.getExpireTime(),
                    "validitySeconds", info.getValiditySeconds(),
                    "phone", info.getPhone(),
                    "name", info.getName()
                ));
            });
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 配置验证接口
     * @param configType 配置类型
     * @param configKey 配置key
     * @param configValue 配置值
     * @return 验证结果
     */
    @PostMapping("/config")
    public ResponseEntity<Map<String, Object>> validateConfig(
            @RequestParam String configType,
            @RequestParam String configKey,
            @RequestParam String configValue) {
        
        // 记录调用来源信息
        String appId = RequestContextUtil.getCurrentAppId();
        String systemName = RequestContextUtil.getCurrentSystemName();
        log.info("配置验证请求 - appId: {}, 系统名称: {}, 配置类型: {}, 配置Key: {}", 
                appId, systemName, configType, configKey);
        
        boolean isValid = configService.validateConfig(configType, configKey, configValue);
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("data", Map.of(
            "configType", configType,
            "configKey", configKey,
            "configValue", configValue,
            "isValid", isValid
        ));
        
        if (isValid) {
            Optional<Config> configInfo = configService.getConfigInfo(configType, configKey, configValue);
            configInfo.ifPresent(info -> {
                response.put("configInfo", Map.of(
                    "remark", info.getRemark(),
                    "version", info.getVersion(),
                    "isAvailable", info.getIsAvailable()
                ));
            });
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 三合一验证接口：配置验证 + 卡密验证 + 数据上报
     * @param request 验证请求参数
     * @return 统一响应结果
     */
    @PostMapping("/combined")
    public ApiResponse<Map<String, Object>> combinedValidation(@RequestBody CombinedValidationRequest request) {
        
        // 记录调用来源信息
        String appId = RequestContextUtil.getCurrentAppId();
        String systemName = RequestContextUtil.getCurrentSystemName();
        log.info("三合一验证请求 - appId: {}, 系统名称: {}, 配置类型: {}, 配置Key: {}, 卡密: {}", 
                appId, systemName, request.getConfigType(), request.getConfigKey(), request.getCardPassword());
        
        Config config;
        try {
            // 1. 配置验证
            config = configService.validateConfigForCombined(request.getConfigType(), request.getConfigKey(), request.getConfigValue());
            log.info("配置验证通过 - type={}, key={}, value={}", 
                    request.getConfigType(), request.getConfigKey(), request.getConfigValue());
        } catch (RuntimeException e) {
            if (e.getMessage().contains("配置不存在")) {
                log.warn("配置验证失败 - 配置不存在: type={}, key={}, value={}", 
                        request.getConfigType(), request.getConfigKey(), request.getConfigValue());
                return ApiResponse.error(ErrorCode.CONFIG_NOT_EXISTS.getCode(), ErrorCode.CONFIG_NOT_EXISTS.getMsg());
            } else if (e.getMessage().contains("配置值不匹配")) {
                log.warn("配置验证失败 - 配置值不匹配: type={}, key={}, value={}", 
                        request.getConfigType(), request.getConfigKey(), request.getConfigValue());
                return ApiResponse.error(ErrorCode.CONFIG_VALUE_MISMATCH.getCode(), ErrorCode.CONFIG_VALUE_MISMATCH.getMsg());
            } else {
                log.error("配置验证异常: {}", e.getMessage());
                return ApiResponse.error(ErrorCode.CONFIG_VALIDATION_FAILED.getCode(), ErrorCode.CONFIG_VALIDATION_FAILED.getMsg());
            }
        }
        
        // 2. 卡密验证
        Optional<CardPassword> cardPasswordOpt = cardPasswordService.getCardPasswordInfo(request.getCardPassword());
        if (cardPasswordOpt.isEmpty()) {
            log.warn("卡密验证失败 - 卡密不存在或已过期: cardPassword={}", request.getCardPassword());
            return ApiResponse.error(ErrorCode.CARD_PASSWORD_NOT_EXISTS.getCode(), ErrorCode.CARD_PASSWORD_NOT_EXISTS.getMsg());
        }
        
        CardPassword cardPassword = cardPasswordOpt.get();
        log.info("卡密验证通过 - cardPassword={}, 有效期至: {}", request.getCardPassword(), cardPassword.getExpireTime());
        
        // 3. 数据上报验证
        if (!userReportService.validateMacAddress(request.getMacAddress())) {
            log.warn("数据上报验证失败 - MAC地址格式错误: macAddress={}", request.getMacAddress());
            return ApiResponse.error(ErrorCode.MAC_ADDRESS_FORMAT_ERROR.getCode(), ErrorCode.MAC_ADDRESS_FORMAT_ERROR.getMsg());
        }
        
        if (!userReportService.validateJsonData(request.getAccountInfo())) {
            log.warn("数据上报验证失败 - 账号信息JSON格式错误: accountInfo={}", request.getAccountInfo());
            return ApiResponse.error(ErrorCode.JSON_DATA_FORMAT_ERROR.getCode(), ErrorCode.JSON_DATA_FORMAT_ERROR.getMsg());
        }
        
        if (!userReportService.validateJsonData(request.getHeroInfo())) {
            log.warn("数据上报验证失败 - 英雄信息JSON格式错误: heroInfo={}", request.getHeroInfo());
            return ApiResponse.error(ErrorCode.JSON_DATA_FORMAT_ERROR.getCode(), ErrorCode.JSON_DATA_FORMAT_ERROR.getMsg());
        }
        
        if (!userReportService.validateJsonData(request.getOtherInfo())) {
            log.warn("数据上报验证失败 - 其他信息JSON格式错误: otherInfo={}", request.getOtherInfo());
            return ApiResponse.error(ErrorCode.JSON_DATA_FORMAT_ERROR.getCode(), ErrorCode.JSON_DATA_FORMAT_ERROR.getMsg());
        }
        
        // 4. 数据上报入库
        UserReport userReport = userReportService.createUserReport(
                request.getMacAddress(),
                request.getAccountInfo(),
                request.getHeroInfo(),
                request.getOtherInfo()
        );
        
        log.info("数据上报成功 - MAC地址: {}, 业务ID: {}", request.getMacAddress(), userReport.getBusinessId());
        
        // 5. 构建响应结果
        Map<String, Object> responseData = new HashMap<>();
        responseData.put("configValidation", Map.of(
                "type", request.getConfigType(),
                "key", request.getConfigKey(),
                "value", request.getConfigValue(),
                "isValid", true,
                "configInfo", Map.of(
                        "remark", config.getRemark(),
                        "version", config.getVersion(),
                        "isAvailable", config.getIsAvailable()
                )
        ));
        
        responseData.put("cardPasswordValidation", Map.of(
                "cardPassword", request.getCardPassword(),
                "isValid", true,
                "cardInfo", Map.of(
                        "expireTime", cardPassword.getExpireTime(),
                        "validitySeconds", cardPassword.getValiditySeconds(),
                        "phone", cardPassword.getPhone(),
                        "name", cardPassword.getName()
                )
        ));
        
        responseData.put("userReport", Map.of(
                "macAddress", request.getMacAddress(),
                "businessId", userReport.getBusinessId(),
                "createTime", userReport.getCreateTime()
        ));
        
        return ApiResponse.success("三合一验证成功", responseData);
    }
}